package com.AndroidUI;

import java.util.ArrayList;

import com.AR_Edificacio.R;
import com.EdificacioAR.AugmentedRealityActivity;
import com.EdificacioAR.DebugLog;
import com.Exceptions.ExternalStorageException;
import com.Data.DataLoader;
import com.Domain.Channel;
import com.Domain.ChannelController;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Debug;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;


public class LayerManagerActivity extends Activity {

	private static final String TAG = "LayerManagerActivity";
	
	/** Called when the activity first starts or the user navigates back
	 * to an activity. */
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
				
		setContentView(R.layout.channel_grid);
				
		loadChannels();
		
		GridView gridView = (GridView) findViewById(R.id.gridview);
		ChannelAdapter channelAdapter = new ChannelAdapter(this);
		
		//Add the channels to the channelAdapter
		ArrayList<Channel> channels = ChannelController.getInstance().getChannelList();
		DebugLog.LOGD(TAG + " - channel list size: " + channels.size());
		for (Channel c : channels) {
			channelAdapter.addChannel(c);
		}

		gridView.setAdapter(channelAdapter);
		
	    gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
				//Toast.makeText(LayerManagerActivity.this, "" + position, Toast.LENGTH_SHORT).show();
				channelSelected(position);
			}
	    });
		
		/*
		setContentView(R.layout.main);

	    GridView gridview = (GridView) findViewById(R.id.gridview);
	    gridview.setAdapter(new ImageAdapter(this));

	    gridview.setOnItemClickListener(new OnItemClickListener() {
	        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
	            Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show();
	        }
	    });
	    */
	}
	
	private void channelSelected(int position) {
		
		// Create the AR Activity and pass the selected channel position
		Intent ARIntent = new Intent(LayerManagerActivity.this, AugmentedRealityActivity.class);
		ARIntent.putExtra("channelPosition", position);
		LayerManagerActivity.this.startActivity(ARIntent);
		
		
	}
	
	private void loadChannels() {
		
		DebugLog.LOGD(TAG + " - loadChannels");
		
		try {
			ArrayList<Channel> channels = DataLoader.loadData();
			ChannelController.getInstance().setChannelList(channels);
		} catch (ExternalStorageException e) {
			DebugLog.LOGE(TAG + " - " + e.getMessage());
		}	
	}
	
}
